import { SerializableLayerObject } from '@/core/layers/base';
import type { Layer } from '@/core/public';
import { createSlice, PayloadAction } from '@reduxjs/toolkit';


interface InitialState {
  list: SerializableLayerObject[],
  active?: SerializableLayerObject
}

const initialState: InitialState = {
  list: [],
  active: undefined
}

type LayerId = number;


export default createSlice({
  name: 'layers',
  initialState,
  reducers: {
    add: (state, action: PayloadAction<Layer>) => {
      const serLayer = action.payload.serialize();
      state.list.push(serLayer)
      state.active = serLayer
    },
    remove: (state, action: PayloadAction<LayerId>) => {
      const index = state.list.findIndex(item => item.id === action.payload)
      state.list.splice(index, 1)
      if(state.list.length > 0) {
        state.active = state.list[Math.max(index-1, 0)]
      }
    },
    update: (state, action: PayloadAction<SerializableLayerObject>) => {
      const index = state.list.findIndex((item) => item.id === action.payload.id);
      if(index > -1) {
        var newItem = {
          ...state.list[index],
          ...action.payload
        }
        state.list.splice(index, 1, newItem)
        if(state.active?.name == action.payload.name) state.active = newItem
      }
    },
    activate: (state, action: PayloadAction<LayerId>) => {
      state.active = state.list.find(item => item.id === action.payload)
    },
    reset: (state, action: PayloadAction<void>) => {
      state.list = []
      state.active = undefined
    },
  },
});